'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const { phone, password } = ctx.request.body
    const result = await ctx.service.user.login({
      phone, password
    })
    if (result.code === 1) {
      const token = this.app.jwt.sign({ phone: phone }, this.app.config.jwt.secret, { expiresIn: 24 * 60 * 60}); // 生成秘钥
      this.ctx.cookies.set('token', token) // 设置cookies
      ctx.response.body = {
        code: 1,
        msg: '登录成功'
      }
    } else {
      ctx.response.body = {
        code: 0,
        msg: result.msg
      }
    }
  }
  async register() {
    // 注册的功能
    const { ctx } = this;
    const { phone, password, code } = ctx.request.body
    if (!code) {
      ctx.response.body = {
        code: 0,
        msg: '验证码错误'
      }
    } else {
      const searchcResult = await ctx.service.user.search(phone)
      console.log('searchResult', searchcResult)
      if (searchcResult.exist) { // 已存在
        ctx.response.body = {
          code: 0,
          msg: '手机号已被注册过'
        }
      } else { // 手机号没有被注册过
        const result = await ctx.service.user.register(phone, password)
        if (result.code === 1) {
          ctx.response.body = {
            code: 1,
            msg: '注册成功'
          }
        } else {
          ctx.response.body = {
            code: 0,
            msg: '注册失败'
          }
        }
      }
    }
  }
}

module.exports = UserController;
